package com.tencent.miniproject.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.miniproject.R;
import com.tencent.miniproject.base.BaseActivity;
import com.tencent.miniproject.constants.Constant;
import com.tencent.miniproject.presenter.PublishInfoPresenter;
import com.tencent.miniproject.presenter.i.IPublishInfoPresenter;
import com.tencent.miniproject.ui.i.IPublishInfoActivity;
import com.tencent.miniproject.utils.PhotoBitmapUtils;
import com.tencent.miniproject.utils.UserInfoUtil;
import com.tencent.miniproject.view.CustomDialog;
import com.tencent.miniproject.view.MoneyEditText;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PublishInfoActivity extends BaseActivity
        implements IPublishInfoActivity, TencentLocationListener {

    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.iv_take_photo)
    ImageView ivTakePhoto;
    @BindView(R.id.iv_user_photo)
    CircleImageView ivUserPhoto;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.et_pic_tag)
    EditText etPicTag;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.et_input_name)
    EditText etInputName;
    @BindView(R.id.et_input_money)
    EditText etInputMoney;
    @BindView(R.id.et_shop_place)
    EditText etShopPlace;
    @BindView(R.id.iv_back)
    ImageView ivBack;

    //presenter
    private IPublishInfoPresenter mPresenter;

    //拍照得到的文件，方便用于上传
    private File mPicFile;

    //腾讯地图定位manager
    private TencentLocationManager mLocationManager;
    private CustomDialog mCustomDialog;

    private static final int CODE_CAMERA_REQUEST = 0xa1;//拍照
    private static final int CODE_RESULT_REQUEST = 0xa2;//最终裁剪后的结果
    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";
    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 600;
    private static int output_Y = 600;

    @Override
    protected int setLayoutResID() {
        return R.layout.activity_publish;
    }

    @Override
    protected void initData() {
        mPresenter = new PublishInfoPresenter(this);
    }

    @Override
    protected void initView() {
        //设置输入金钱过滤规则
        setPublishButtonCanClick(false);
        MoneyEditText.setPricePoint(etInputMoney);
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
            };

            if (checkSelfPermission(permissions[0]) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, Constant.GET_POSITION);
            } else {
                setPositionListener();
            }
        } else {
            setPositionListener();
        }
        Glide.with(this).load(UserInfoUtil.getUserHeadUrl(this)).into(ivUserPhoto);
        tvUserName.setText(UserInfoUtil.getUserName(this));
    }

    @Override
    protected void initListener() {

    }

    private void setPositionListener() {
        TencentLocationRequest request = TencentLocationRequest.create();
        request.setRequestLevel(3);
        //间隔5s
        request.setInterval(5000);
        mLocationManager = TencentLocationManager.getInstance(this);
        mLocationManager.requestLocationUpdates(request, this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationManager.removeUpdates(this);
        if (mCustomDialog != null) {
            mCustomDialog.dismiss();
        }
    }

    private String TAG = "ning";

    @OnClick({R.id.iv_photo, R.id.iv_take_photo, R.id.tv_publish, R.id.iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_photo:
                Log.i(TAG, "onClick: ");

////                mPicFile = new File("/storage/emulated/0/Q_bill/publish.png");
//                mPicFile = new File("/storage/emulated/0/Qmap/cache.info");
//                Log.i(TAG, "onClick: " + mPicFile.length());
//                mPresenter.getPicTagFromNet(mPicFile);

//                mPresenter.takePhoto(PublishInfoActivity.this, mImageUri);
                break;
            case R.id.iv_take_photo:
                Log.i(TAG, "onClick:22 ");
                applyWritePermissionAndTakePhoto();
                break;
            case R.id.tv_publish:
                //点击发布按钮,dialog
                //发布的时候要保证以下参数不为空
                if (!mPresenter.canPublishData(mPicFile, etShopPlace.getText().toString(),
                        mLocationManager.getLastKnownLocation().getLongitude(),
                        mLocationManager.getLastKnownLocation().getLatitude(),
                        etPicTag.getText().toString(), etInputMoney.getText().toString())) {
                    showToast("参数不正确，请确认参数是否为空");
                    return;
                }
                mCustomDialog = new CustomDialog(PublishInfoActivity.this);
                mCustomDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mPresenter.publishData(PublishInfoActivity.this, mPresenter.getPublishBeen(etContent.getText().toString(),
                                etShopPlace.getText().toString(), mLocationManager.getLastKnownLocation().getLongitude(),
                                mLocationManager.getLastKnownLocation().getLatitude(), etInputName.getText().toString(),
                                etPicTag.getText().toString(), new Date(), etInputMoney.getText().toString(),
                                getDistrict()),
                                mPicFile);
                    }
                }).start();
                break;
            case R.id.iv_back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 获取省市区，分号隔开
     *
     * @return string
     */
    private String getDistrict() {
        return mLocationManager.getLastKnownLocation().getDistrict();
    }


    /**
     * 从presenter请求跳转页面
     *
     * @param intent 传入intent
     */
    @Override
    public void startActivityFromPresenter(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    /**
     * 显示标签
     *
     * @param tag tag
     */
    @Override
    public void showTagFromNet(String tag) {
        etPicTag.setText(tag);
    }

    /**
     * 发布之后的结果
     */
    @Override
    public void showPublishResult(boolean success) {
        mCustomDialog.dismiss();
        if (success) {
            //刷新上一页面
            setResult(Constant.REFRESH_PUBLISH_SUCCESS_FINISH);
            finish();
        } else {
            showToast("发布失败");
        }
    }

    /**
     * 打开发布按钮
     * @param canClick bool
     */
    @Override
    public void setPublishButtonCanClick(boolean canClick) {
        if (canClick){
            tvPublish.setClickable(true);
            tvPublish.setTextColor(Color.WHITE);
        }else {
            tvPublish.setClickable(false);
            tvPublish.setTextColor(Color.GRAY);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == Constant.TAKE_PHOTO) {
            //请求拍照
            if (resultCode == RESULT_OK) {
//                //读取压缩后的图片
//                Bitmap bitmap = PhotoBitmapUtils.getCompressPhoto(mPicFile.getAbsolutePath());
//                //旋转90度
//                bitmap = PhotoBitmapUtils.rotaingImageView(90, bitmap);
//                ivPhoto.setImageBitmap(bitmap);
//
//                //显示之后发送图片文件到后台识别图片
//                mPresenter.getPicTagFromNet(this, mPicFile);

                // 得到修复后的照片路径,旋转
                try {
                    Log.i(TAG, "onActivityResult1: " + System.currentTimeMillis());
                    Log.i(TAG, "onActivityResult33: " + mFileName);
                    String filepath = PhotoBitmapUtils.amendRotatePhoto(mFileName, this);
                    Log.i(TAG, "onActivityResult2: " + System.currentTimeMillis());
                    comparessPicture(filepath);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        } else if (requestCode == Constant.GET_POSITION) {
            setPositionListener();
        }
    }

    /**
     * 压缩图片并上传，进行识别
     * @param filePath 文件路径
     */
    private void comparessPicture(String filePath) {
        Luban.with(this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(mPicFile.getParent())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        Log.i(TAG, "onStart: ");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.i(TAG, "onActivityResult3: " + System.currentTimeMillis());
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                        ivPhoto.setImageBitmap(bitmap);
                        mPresenter.getPicTagFromNet(file);
                        mPicFile = file;
                        Log.i(TAG, "onActivityResult4: " + System.currentTimeMillis());
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        Log.i(TAG, "onError: " + e.getMessage());
                    }
                }).launch();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            useCamera();
        }
        if (requestCode == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            showCamera();
        } else {
            // 没有获取 到权限，从新请求，或者关闭app
            Toast.makeText(this, "需要存储权限", Toast.LENGTH_SHORT).show();
        }
    }

    public void applyWritePermissionAndTakePhoto() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT >= 23) {
            int check = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED) {
                //调用相机
                useCamera();
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } else {
            useCamera();
        }
    }

    /**
     * 使用相机
     */
    private void useCamera() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 2);
                return;
            } else {
                showCamera();
            }
        } else {
            showCamera();
        }
    }

    //文件名
    private String mFileName;

    /**
     * 开始拍照
     */
    private void showCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 设置图片要保存的 根路径+文件名
        mFileName = PhotoBitmapUtils.getPhotoFileName(this);
        Log.i(TAG, "showCamera:path  " + mFileName);
//        mPicFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
//                + "/Q_bill/publish.png");
        mPicFile = new File(mFileName);
        if (!mPicFile.exists()) {
            try {
                mPicFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.tencent.miniproject.provider", mPicFile);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, Constant.TAKE_PHOTO);
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        Log.i(TAG, "onLocationChanged11: " + tencentLocation.getAddress() + " " + i + " " + s);
        if (i == STATUS_DISABLED) {
            etShopPlace.setText(tencentLocation.getAddress());
            etShopPlace.setSelection(etShopPlace.getText().length());
            mLocationManager.removeUpdates(this);
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {
        Log.i(TAG, "onLocationChanged22: " + s + " " + s1);
    }

}
